﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsFlower.Model;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.AxHost;

namespace WindowsFormsFlower
{
    
    public partial class Form1 : Form
    {
        Random random = new Random();
        Icon icon ;
        public Form1()
        {
            InitializeComponent();
            //ApplySmoothRoundCorners(20);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            tblabel.Text = "生日快乐, 新年快乐, 万事如意, 心想事成, 身体健康, 学业进步, 工作顺利, 财源广进, 阖家幸福, 笑口常开, 青春永驻, 平安喜乐, 大吉大利, 福星高照, 步步高升, 龙马精神, 年年有余, 金玉满堂, 幸福美满, 前程似锦,";
            // 加载嵌入的图标资源
            try
            {
                // 获取当前程序集
                Assembly assembly = Assembly.GetExecutingAssembly();
                // 资源名称：命名空间.文件名.扩展名
                string resourceName = "WindowsFormsFlower.1.ico";

                // 获取资源流
                using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                {
                    if (stream != null)
                    {
                        icon = new Icon(stream);
                    }
                    else
                    {
                        throw new FileNotFoundException($"找不到嵌入资源: {resourceName}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载图标失败: {ex.Message}");
                this.Icon = SystemIcons.Application; // 使用默认图标
            }
        }
        private void ApplySmoothRoundCorners(int cornerRadius)
        {
            // 创建图形路径
            GraphicsPath path = new GraphicsPath();
            // 设置高质量渲染
            this.DoubleBuffered = true;

            // 创建更平滑的圆角矩形
            Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);

            // 使用贝塞尔曲线创建更平滑的角
            int diameter = cornerRadius * 2;

            path.AddArc(rect.X, rect.Y, diameter, diameter, 180, 90);
            path.AddArc(rect.Width - diameter, rect.Y, diameter, diameter, 270, 90);
            path.AddArc(rect.Width - diameter, rect.Height - diameter, diameter, diameter, 0, 90);
            path.AddArc(rect.X, rect.Height - diameter, diameter, diameter, 90, 90);
            path.CloseAllFigures();

            this.Region = new Region(path);
        }
        // 生成爱心形状的坐标点
        private List<Point> GenerateHeartPoints(int centerX, int centerY, int heartSize, int pointCount)
        {
            List<Point> points = new List<Point>();
            for (int i = 0; i < pointCount; i++)
            {
                double t = 2 * Math.PI * i / pointCount;
                // 爱心曲线方程
                double x = 16 * Math.Pow(Math.Sin(t), 3);
                double y = 13 * Math.Cos(t) - 5 * Math.Cos(2 * t) - 2 * Math.Cos(3 * t) - Math.Cos(4 * t);
                // 更好的缩放方案：将坐标归一化到合适的范围
                double scale = heartSize / 20.0; // 控制爱心大小
                int pointX = centerX + (int)(x * scale);
                int pointY = centerY - (int)(y * scale);
                points.Add(new Point(pointX, pointY));
            }
            return points;
        }
        private async Task CreateForms_Model_1()
        {
            int centerX = Screen.PrimaryScreen.WorkingArea.Width / 2;
            int centerY = Screen.PrimaryScreen.WorkingArea.Height / 2;
            int pointNum = int.Parse(tbNum.Text);
            List<Point> points = GenerateHeartPoints(centerX - 100, centerY - 100, int.Parse(tbheart.Text), pointNum);
            FlowerApp.Instance.formLabelList = new List<FormLabel>(pointNum);
            for (int i = 0; i < pointNum; i++)
            {
                if (FlowerApp.Instance.FormState == CurrentState.Stop)
                {
                    return;
                }
                FormLabel form = new FormLabel(FlowerApp.Instance.labelList[random.Next(0, FlowerApp.Instance.labelList.Count)]);
                form.StartPosition = FormStartPosition.Manual;
                form.Location = points[i];
                form.MaximizeBox = false;
                form.Icon = icon;
                form.FormBorderStyle = FormBorderStyle.FixedDialog;
                form.BackColor = FlowerApp.Instance.lightColors[random.Next(0, FlowerApp.Instance.lightColors.Count)];
                form.AddPetalEffectToForm();//增加花瓣效果
                //form.Size = new Size(120, 80); // 建议设置窗体大小
                FlowerApp.Instance.formLabelList.Add(form); // 正确：使用Add方法添加
                form.Show();
                await Task.Delay(int.Parse(tbTimer.Text));
            }
            List<Point> points1= RandomPoints.GenerateRandomPositions(pointNum);
            await FlowerApp.Instance.formLabelList.SmoothMoveAll(points1);

        }
        private async Task CreateForms_Model_2()
        {
            int pointNum = int.Parse(tbNum.Text);
            List<Point> points1 = RandomPoints.GenerateRandomPositions(pointNum);
            FlowerApp.Instance.formLabelList = new List<FormLabel>(pointNum);
            for (int i = 0; i < pointNum; i++)
            {
                if (FlowerApp.Instance.FormState == CurrentState.Stop)
                {
                    return;
                }
                FormLabel form = new FormLabel(FlowerApp.Instance.labelList[random.Next(0, FlowerApp.Instance.labelList.Count)]);
                form.StartPosition = FormStartPosition.Manual;
                form.Location = points1[i];
                form.Icon = icon;
                form.FormBorderStyle = FormBorderStyle.FixedDialog;
                form.MaximizeBox = false;
                form.BackColor = FlowerApp.Instance.lightColors[random.Next(0, FlowerApp.Instance.lightColors.Count)];
                form.AddPetalEffectToForm();//增加花瓣效果
                FlowerApp.Instance.formLabelList.Add(form); // 正确：使用Add方法添加
                form.Show();
                await Task.Delay(int.Parse(tbTimer.Text));
            }
            int centerX = Screen.PrimaryScreen.WorkingArea.Width / 2;
            int centerY = Screen.PrimaryScreen.WorkingArea.Height / 2;
            List<Point> points = GenerateHeartPoints(centerX - 100, centerY - 100, int.Parse(tbheart.Text), pointNum);
            await FlowerApp.Instance.formLabelList.SmoothMoveAll(points);
        }
        private async Task CreateForms_Model_3()
        {
            int pointNum = int.Parse(tbNum.Text);
            List<Point> points1 = RandomPoints.GenerateRandomPositions(pointNum);
            FlowerApp.Instance.formLabelList = new List<FormLabel>(pointNum);
            for (int i = 0; i < pointNum; i++)
            {
                if (FlowerApp.Instance.FormState == CurrentState.Stop)
                {
                    return;
                }
                FormLabel form = new FormLabel(FlowerApp.Instance.labelList[random.Next(0, FlowerApp.Instance.labelList.Count)]);
                form.StartPosition = FormStartPosition.Manual;
                form.Location = points1[i];
                form.FormBorderStyle = FormBorderStyle.FixedDialog;
                form.MaximizeBox = false;
                form.Icon = icon;
                form.BackColor = FlowerApp.Instance.lightColors[random.Next(0, FlowerApp.Instance.lightColors.Count)];
                form.AddPetalEffectToForm();//增加花瓣效果
                FlowerApp.Instance.formLabelList.Add(form); // 正确：使用Add方法添加
                form.Show();
                await Task.Delay(int.Parse(tbTimer.Text));
            }
        }
        //开始按钮
        private async void btnStart_Click(object sender, EventArgs e)
        {
            if (FlowerApp.Instance.FormState == CurrentState.DoneStart)
            {
                DialogResult result = MessageBox.Show(
                    "程序正在运行中，是否要停止当前操作？",
                    "提示",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    btnClose_Click(sender,e);
                }
                return;
            }
            this.Hide();
            FlowerApp.Instance.FormState = CurrentState.Start;
            string Model=cbmodel.Text;
            //文字解析
            FlowerApp.Instance.labelList = tblabel.Text.Split(new char[] { ',','，' }, StringSplitOptions.RemoveEmptyEntries)
                                        .Select(s => s.Trim())
                                        .Where(s => !string.IsNullOrWhiteSpace(s))
                                        .ToList();
            FlowerApp.Instance.MoveValue = int.Parse(tbmove.Text);
            switch (Model)
            {
                case "模式一":
                    FlowerApp.Instance.FormModel = CurrentModel.Model_1;
                    await CreateForms_Model_1();
                    break;
                case "模式二":
                    FlowerApp.Instance.FormModel = CurrentModel.Model_2;
                    await CreateForms_Model_2();
                    break;
                case "模式三":
                    FlowerApp.Instance.FormModel = CurrentModel.Model_3;
                    await CreateForms_Model_3();
                    break;
                default:
                    break;
            }
            FlowerApp.Instance.FormModel = CurrentModel.None;
            FlowerApp.Instance.FormState = CurrentState.DoneStart;
            await Task.Delay(2000);
            this.Show();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (FlowerApp.Instance.FormState != CurrentState.DoneStart)
            {
                return;
            }
            FlowerApp.Instance.FormState = CurrentState.Stop;
            foreach (FormLabel form in FlowerApp.Instance.formLabelList)
            {
                if (!form.IsDisposed)
                {
                    form.Close();
                }
            }
            FlowerApp.Instance.formLabelList.Clear(); // 清空列表
            FlowerApp.Instance.FormModel = CurrentModel.None;
            FlowerApp.Instance.FormState = CurrentState.DoneStop;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.TopMost = true;
            // 开始按钮
            btnStart.BackColor = Color.FromArgb(173, 216, 230); // 浅蓝色
            // 关闭按钮  
            btnClose.BackColor = Color.FromArgb(221, 160, 221); // 浅紫色
        }
    }
}
